package com.baseweb.webadmin.controller.web;

import com.baseweb.webadmin.controller.BaseController;
import com.baseweb.webadmin.core.constants.BaseState;
import com.baseweb.webadmin.core.constants.ChannelType;
import com.baseweb.webadmin.core.model.pojo.*;
import com.baseweb.webadmin.service.UserService;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dengsy on 2017-06-23.
 * 开通城市区域
 */
@Controller
@RequestMapping(value = "/cityWeb")
public class CityWebController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(MainWebController.class);
    private final static String SESSION_CHECK_CODE = "checkCode";

    @Autowired
    private UserService userService;

    /**
     * 根据角用户查询开通的区域
     */
    @RequestMapping(value = "/findAllAreaByUserId", method = RequestMethod.POST)
    public String findAllAreaByUserId(Model model,@RequestParam("userId") int userId){
        List<ByOpenCity> byOpenAreaList = userService.findAllAreaByUserId(userId);
        model.addAttribute("byOpenAreaList", byOpenAreaList);
        return "";
    }

    /**
     * 根据角用户查询开通的城市
     */
    @RequestMapping(value = "/findAllCityByUserId", method = RequestMethod.POST)
    public String findAllCityByUserId(Model model,@RequestParam("userId") int userId){
        List<ByOpenCity> byOpenCityList = userService.findAllCityByUserId(userId);
        model.addAttribute("byOpenCityList", byOpenCityList);
        return "";
    }

    /**
     *用户给开通城市，区域授权
     */
    @RequestMapping(value = "/insertRoleOpenCity", method = RequestMethod.POST)
    public String insertRoleOpenCity(Model model,@RequestParam("userId") int userId,@RequestParam("openCitys") String openCitys){
        String isOK = "NO";
        if(!"".equals(openCitys)){
            String[] citys=openCitys.split(",");
            //删除已有
            userService.deleteRoleOpenCityByRoleId(userId);
            //添加
            for(int i=0;i<citys.length;i++){
                if(userService.insertRoleOpenCity(userId,Integer.valueOf(citys[i])) == 1){
                    isOK = "OK";
                }
            }
        }
        model.addAttribute("isOK", isOK);
        return "";
    }

    /**
     * 获取开通省。城市
     */
    @RequestMapping(value = "/findProvinceOpen", method = RequestMethod.POST)
    public String findProvinceOpen(Model model,@RequestParam("where") String where){
        List<ByProvince> byProvinceList = new ArrayList<ByProvince>();
        List<ByOpenCity> byOpenCityList = userService.findAllProvinceCityListByWhere(where);
        String province = "";
        ByProvince provinces = new ByProvince();
        int i = 0;
        List<ByCity> cityList = new ArrayList<ByCity>();
        for(ByOpenCity byOpenCity : byOpenCityList){
            ByCity byCity = new ByCity();
            byCity.setName(byOpenCity.getCity());

            if(province.equals(byOpenCity.getProvince())){
                cityList.add(byCity);
                provinces.setByCityList(cityList);
            }else {
                if(!"".equals(province) || i == 1){
                    byProvinceList.add(provinces);
                }
                provinces = new ByProvince();
                cityList = new ArrayList<ByCity>();
                cityList.add(byCity);

                provinces.setName(byOpenCity.getProvince());
                provinces.setByCityList(cityList);
            }

            if(i == (byOpenCityList.size()-1)){
                byProvinceList.add(provinces);
            }
            province = byOpenCity.getProvince();
            i++;
        }

        model.addAttribute("byProvinceList", byProvinceList);
        return "";
    }

    /**
     * 获取开通城市，区域
     */
    @RequestMapping(value = "/findCitiesOpen", method = RequestMethod.POST)
    public String findCitiesOpen(Model model,@RequestParam("userId") int userId,@RequestParam("where") String where) {
        List<ByCity> byCityList = new ArrayList<ByCity>();

        if(userId == 0){
            userId = 1;
        }

        List<ByOpenCity> byOpenCityList = userService.findAllListByWhere(userId,where);
        String city = "";
        ByCity citys = new ByCity();
        int i = 0;
        List<ByArea> areaList = new ArrayList<ByArea>();
        for(ByOpenCity byOpenCity : byOpenCityList){
            ByArea area = new ByArea();
            area.setId(byOpenCity.getId());
            area.setName(byOpenCity.getArea());
            area.setOpenType(byOpenCity.getOpenType());

            if(city.equals(byOpenCity.getCity())){
                areaList.add(area);
                citys.setByAreaList(areaList);
            }else {
                if(!"".equals(city) || i == 1){
                    byCityList.add(citys);
                }
                citys = new ByCity();
                areaList = new ArrayList<ByArea>();
                areaList.add(area);

                citys.setId(byOpenCity.getId());
                citys.setName(byOpenCity.getCity());
                citys.setByAreaList(areaList);
            }

            if(i == (byOpenCityList.size()-1)){
                byCityList.add(citys);
            }
            city = byOpenCity.getCity();
            i++;
        }

        model.addAttribute("byCityList", byCityList);
        return "";
    }

    /**
     * 删除开通城市
     */
    @RequestMapping(value = "/deleteOpenCityByPrimaryKey", method = RequestMethod.GET)
    public String deleteOpenCityByPrimaryKey(Model model,@RequestParam("opentCityId") int opentCityId){
        String isOK = "NO";
        if(userService.deleteOpenCityByPrimaryKey(opentCityId) == 1){
            //删除关系表
            if(userService.deleteRoleOpenCityByOpenCityId(opentCityId) > 0){
                isOK = "OK";
            }
        }else {
            model.addAttribute("msg","删除失败");
        }
        model.addAttribute("isOK",isOK);
        return "";
    }

    /**
     * 添加/修改
     */
    @RequestMapping(value = "/insertCtiy", method = RequestMethod.POST)
    public String insertCtiy(Model model,@ModelAttribute()ByOpenCity byOpenCity){
        String isOK = "NO";
        if(byOpenCity.getId() == null || "".equals(byOpenCity.getId())){
            ByOpenCity byOpenCityR = userService.findByProvinceCityArea(byOpenCity.getProvince(),byOpenCity.getCity(),byOpenCity.getArea());
            if(byOpenCityR != null){
                model.addAttribute("msg","已经存在");
            }else {
                byOpenCity.setStatus(1);
                byOpenCity.setCreateTime(new DateTime());
                byOpenCity.setUpdateTime(new DateTime());
                if(userService.insertSelectiveCity(byOpenCity) == 1){
                    //给超级管理员添加权限
                    ByOpenCity byOpenCityV = userService.findByProvinceCityArea(byOpenCity.getProvince(),byOpenCity.getCity(),byOpenCity.getArea());
                    if(userService.insertRoleOpenCity(1,byOpenCityV.getId()) == 1){
                        isOK = "OK";
                    }
                }else {
                    model.addAttribute("msg","添加失败");
                }
            }
        }else {
            byOpenCity.setUpdateTime(new DateTime());
            if(userService.updateByPrimaryKeySelectiveCity(byOpenCity) == 1){
                isOK = "OK";
            }else {
                model.addAttribute("msg","修改失败");
            }
        }
        model.addAttribute("isOK",isOK);
        return "";
    }

    /**
     * 查询所有省市区列表带分页和查询条件、支持模糊
     */
    @RequestMapping(value = "/findAllListPageByWhere", method = RequestMethod.POST)
    public String findAllListPageByWhere(Model model, @RequestParam("page") int page, @RequestParam("pageNum") int pageNum,@RequestParam("where") String where){
        List<ByOpenCity> list = userService.findAllListPageByWhere(where,(page-1)*pageNum,pageNum);
        //总记录数
        int numSum = userService.countAllListPageByWhere(where);
        //总页数
        int pageSum = (numSum>pageNum?(numSum/pageNum):1);
        if(numSum % pageNum > 0 && numSum>pageNum){
            pageSum += 1;
        }
        model.addAttribute("openCityList",list);
        model.addAttribute("numSum",numSum);
        model.addAttribute("pageSum",pageSum);
        return "";
    }

    /**
     * 查询所有用户服务城市列表带分页和查询条件、支持模糊
     */
    @RequestMapping(value = "/findAllUserListPageByWhere", method = RequestMethod.POST)
    public String findAllUserListPageByWhere(Model model,@RequestParam("page") int page, @RequestParam("pageNum") int pageNum,@RequestParam("userId") int userId,@RequestParam("where") String where){
        List<ByOpenCity> list = userService.findAllUserListPageByWhere(userId,where,(page-1)*pageNum,pageNum);
        //总记录数
        int numSum = userService.countAllUesrListPageByWhere(userId,where);
        //总页数
        int pageSum = (numSum>pageNum?(numSum/pageNum):1);
        if(numSum % pageNum > 0 && numSum>pageNum){
            pageSum += 1;
        }
        model.addAttribute("openCityList",list);
        model.addAttribute("numSum",numSum);
        model.addAttribute("pageSum",pageSum);
        return "";
    }

    /**
     * 添加/修改 用户服务城市
     */
    @RequestMapping(value = "/insertUserCtiy", method = RequestMethod.POST)
    public String insertUserCtiy(Model model,@ModelAttribute()ByOpenCity byOpenCity){
        String isOK = "NO";
        if(byOpenCity.getId() == null || "".equals(byOpenCity.getId())){
            ByOpenCity byOpenCityR = userService.findByUserIdProvinceCityArea(byOpenCity.getProvince(),byOpenCity.getCity(),byOpenCity.getArea(),byOpenCity.getUserId());
            if(byOpenCityR != null){
                model.addAttribute("msg","已经存在");
            }else {
                byOpenCity.setStatus(1);
                byOpenCity.setCreateTime(new DateTime());
                byOpenCity.setUpdateTime(new DateTime());
                if(userService.insertUserOpenCity(byOpenCity) == 1){
                    isOK = "OK";
                }else {
                    model.addAttribute("msg","添加失败");
                }
            }
        }
        model.addAttribute("isOK",isOK);
        return "";
    }

    /**
     * 删除用户服务城市
     */
    @RequestMapping(value = "/deleteUserOpenCityByPrimaryKey", method = RequestMethod.GET)
    public String deleteUserOpenCityByPrimaryKey(Model model,@RequestParam("opentCityId") int opentCityId){
        String isOK = "NO";
        if(userService.deleteUserOpenCityById(opentCityId) == 1){
            isOK = "OK";
        }else {
            model.addAttribute("msg","删除失败");
        }
        model.addAttribute("isOK",isOK);
        return "";
    }

    /**
     * 查询所有省份
     */
    @RequestMapping(value = "/findAllProvince", method = RequestMethod.GET)
    public String findAllProvince(Model model){

        List<ByOpenCity> byOpenCityList = userService.findAllProvince();
        model.addAttribute("byOpenCityList", byOpenCityList);
        return "";
    }

    /**
     * 根据省份查询所有市
     */
    @RequestMapping(value = "/findAllCityByProvince", method = RequestMethod.POST)
    public String findAllCityByProvince(Model model, @ModelAttribute()ByOpenCity byOpenCity){

        List<ByOpenCity> byOpenCityList = userService.findAllCityByProvince(byOpenCity.getProvince());
        model.addAttribute("byOpenCityList", byOpenCityList);
        return "";
    }

    /**
     * 根据市查询所有区
     */
    @RequestMapping(value = "/findAllAreaByCity", method = RequestMethod.POST)
    public String findAllAreaByCity(Model model, @ModelAttribute()ByOpenCity byOpenCity){

        List<ByOpenCity> byOpenCityList = userService.findAllAreaByCity(byOpenCity.getCity());
        model.addAttribute("byOpenCityList", byOpenCityList);
        return "";
    }
}
